package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.anlia.library.group.GroupItem;
import com.anlia.library.group.GroupItemDecoration;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.TextViewUtils;
import com.dindang.propertyfee.mvp.contract.PropertyFeeRecordContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.FeeRecordViewAdapter;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import in.srain.cube.views.ptr2.PtrDefaultHandler2;
import in.srain.cube.views.ptr2.PtrFrameLayout;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@FragmentScope
public class PropertyFeeRecordPresenter extends BasePresenter<PropertyFeeRecordContract.Model, PropertyFeeRecordContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private boolean isFirst = true;
    private int LIMIT = 10;
    private PropertyCharge.Record4ClientParam mParam = new PropertyCharge.Record4ClientParam(LIMIT);
    private List<PropertyCharge.Record4Client.FeeList> mList = new ArrayList<>();
    private List<PropertyCharge.Record4Client> mRecord4ClientList = new ArrayList<>();
    private Map<String, PropertyCharge.TotalData> mTotalDataMaps = new LinkedHashMap<>();
    private FeeRecordViewAdapter mAdapter;

    @Inject
    public PropertyFeeRecordPresenter(PropertyFeeRecordContract.Model model, PropertyFeeRecordContract.View rootView) {
        super(model, rootView);
    }

    public void setData(Object data) {
        switch (data.toString()) {
            case "init":
                if(isFirst){
//                    getDate();
                    queryRecord4Client();
                    isFirst = false;
                }
                break;
            case "refresh":
                break;
        }
    }

    public void init() {
        mRootView.getRecyclerview().setLayoutManager(new LinearLayoutManager(mRootView.getFragment().getActivity()));
        initAdapter();
        initListener();
    }

    private void initAdapter() {
        mAdapter = new FeeRecordViewAdapter(mList
                , new FeeRecordViewAdapter.OnOnClickListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.Record4Client.FeeList feeList = mList.get(position);
                ARouter.getInstance().build("/propertyfee/activity/PaymentDetailsActivity")
                        .withString(AppConst.ID, feeList.l_id)
                        .navigation();
            }
        });
        mRootView.getRecyclerview().setAdapter(mAdapter);
    }

    private void initListener() {
        mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
        mRootView.getPtrclassicframelayout().disableWhenHorizontalMove(true);
        mRootView.getPtrclassicframelayout().setLastUpdateTimeRelateObject(this);
        mRootView.getPtrclassicframelayout().setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                queryRecord4Client();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mParam.page = 0;
                queryRecord4Client();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, content, footer);
            }
        });
    }

    /**
     * 查询收费记录
     */
    private void queryRecord4Client() {
        mModel.queryRecord4Client(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {
        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.Record4Client>>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<List<PropertyCharge.Record4Client>> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    mRootView.getEmptyLayout().ERROR_TIP = response.getStatuMsg();
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                    return;
                }
                if(mParam.page == 0){
                    mList.clear();
                    mRecord4ClientList.clear();
                    mRecord4ClientList.addAll(response.getData());
                }else{
                    for (PropertyCharge.Record4Client record4Client : response.getData()) {
                        if(record4Client.time.equals(mRecord4ClientList.get(mRecord4ClientList.size() - 1).time)){
                            mRecord4ClientList.get(mRecord4ClientList.size() - 1).list.addAll(record4Client.list);
                        }else{
                            mRecord4ClientList.add(record4Client);
                        }
                    }
                }

                List<PropertyCharge.Record4Client.FeeList> feeLists = new ArrayList<>();

                for (PropertyCharge.Record4Client record4Client : response.getData()) {
                    feeLists.addAll(record4Client.list);
                }
                mList.addAll(feeLists);

                if(feeLists.size() < LIMIT){
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.REFRESH);
                }else{
                    mRootView.getPtrclassicframelayout().setMode(PtrFrameLayout.Mode.BOTH);
                    mParam.page++;
                }

                if(mList.size() == 0){
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
                }else{
                    mRootView.getEmptyLayout().hide();
                }
                mAdapter.notifyDataSetChanged();
                mRootView.getRecyclerview().removeItemDecoration(groupItemDecoration);
                groupItemDecoration = null;
                initItemDecoration();
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                if(mRootView.getPtrclassicframelayout().isRefreshing()){
                    mRootView.getPtrclassicframelayout().refreshComplete();
                }
            }
        });
    }

    GroupItemDecoration groupItemDecoration;
    private void initItemDecoration(){
        LayoutInflater layoutInflater = LayoutInflater.from(mRootView.getFragment().getActivity());
        View view = layoutInflater.inflate(R.layout.propertyfee_item_group,null);
        groupItemDecoration = new GroupItemDecoration(mRootView.getFragment().getActivity(), view, new GroupItemDecoration.DecorationCallback() {
            @Override
            public void setGroup(List<GroupItem> groupList) {
                //设置分组，例如：
                GroupItem groupItem;
                int startPosition = 0;
                for (PropertyCharge.Record4Client record4Client : mRecord4ClientList) {
                    groupItem = new GroupItem(startPosition);
                    groupItem.setData("data",record4Client.time);
                    groupItem.setData("total",record4Client.total);
                    groupItem.setAmount(record4Client.sumAmount);
                    groupList.add(groupItem);
                    startPosition+=record4Client.list.size();
                }
            }

            @Override
            public void buildGroupView(View groupView, GroupItem groupItem) {
                //构建GroupView，通过view.findViewById找到内部控件，例如
                TextView tv_data = groupView.findViewById(R.id.tv_data);
                tv_data.setText(groupItem.getData("data").toString());
                TextView tv_total = groupView.findViewById(R.id.tv_total);
                tv_total.setText(TextViewUtils.getAmount3(groupItem.getData("total").toString(),groupItem.getAmount()));
            }
        });
        mRootView.getRecyclerview().addItemDecoration(groupItemDecoration);
    }

    /**
     * 这个是用来取出同一时间用的
     * @param list
     */
    private void getDataItem(List<PropertyCharge.Total> list){
        for (PropertyCharge.Total total : list) {
            if(mTotalDataMaps.containsKey(total.paymentDate)){
                PropertyCharge.TotalData totalData = mTotalDataMaps.get(total.paymentDate);
                totalData.addTotal(total);
            }else{
                mTotalDataMaps.put(total.paymentDate, new PropertyCharge.TotalData(total.total, total));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;

        this.mList = null;
        this.mAdapter = null;
        this.mTotalDataMaps = null;
        this.mParam = null;
    }

}
